#include "testbroadcast.h"

#include <QHostAddress> 
#include <QNetworkInterface>



namespace
{
    const int g_port{ 12345 };
#define BROADCAST_MODE 0
}

void testbroadcast::on_pushButton_multicast_clicked()
{
    QString _str{ ui.lineEdit->text() };
    if (m_sender)
    {
        m_sender->writeDatagram(_str.toLocal8Bit(), QHostAddress("225.1.1.2"), g_port);
        ui.plainTextEdit->appendPlainText(_str);
    }
}

void testbroadcast::OnReadDatagram()
{
    if (m_receiver)
    {
        auto _size = m_receiver->pendingDatagramSize();
        QByteArray _array{};
        _array.resize(_size);
        m_receiver->readDatagram(_array.data(), _size);
        ui.plainTextEdit->appendPlainText(_array);
    }
}

void testbroadcast::on_pushButton_broadcast_clicked()
{
    QString _str{ ui.lineEdit->text() };
    if (m_sender)
    {
        m_sender->writeDatagram(_str.toLocal8Bit(),QHostAddress::Broadcast,g_port);
        ui.plainTextEdit->appendPlainText(_str);
    }
}

testbroadcast::testbroadcast(QWidget *parent)
    : QMainWindow(parent)
    , m_sender{}
    , m_receiver{}
{
    ui.setupUi(this);
    OnInitDialog();
}

testbroadcast::~testbroadcast()
{
}

void testbroadcast::OnInitDialog()
{
    InitSocket();
}

void testbroadcast::InitSocket()
{
    if (nullptr == m_sender)
        m_sender = new QUdpSocket(this);
    Q_ASSERT(m_sender);
    if (nullptr == m_receiver)
        m_receiver = new QUdpSocket(this);
    Q_ASSERT(m_receiver);
#if BROADCAST_MODE
    m_receiver->bind(g_port, QUdpSocket::ReuseAddressHint);
#else
    m_receiver->bind(QHostAddress::AnyIPv4, g_port, QUdpSocket::ReuseAddressHint|QUdpSocket::ShareAddress);
    m_receiver->joinMulticastGroup(QHostAddress("225.1.1.2"));
    auto _list_interface = QNetworkInterface::allInterfaces();
    //m_receiver->setMulticastInterface(_list_interface.at(0));
#endif // BROADCAST_MODE

    
    connect(m_receiver, &QIODevice::readyRead, this, &testbroadcast::OnReadDatagram);
}
